package com.ruoyi.web.controller.system;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.common.api.MiniAppApi;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.domain.miniapp.MiniApp;
import com.ruoyi.common.core.domain.miniapp.WxLoginBody;
import com.ruoyi.common.exception.MiniAppException;
import com.ruoyi.common.security.annotation.Anonymous;
import com.ruoyi.common.security.service.MiniAppLoginService;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpHeaders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;


@Slf4j
@RestController
@RequestMapping("/miniapp")
public class WxLoginController
{

    @Autowired
    private MiniAppLoginService miniAppLoginService;

    @Autowired
    private MiniAppApi miniAppService;

    @PostMapping("/wxMiniLogin")
    public R wxMiniLogin(@RequestBody WxLoginBody wxLoginBody) throws MiniAppException
    {
        JSONObject data = miniAppLoginService.wxMiniLogin(wxLoginBody);
        return R.ok(data);
    }


    @Anonymous
    @PostMapping("/selectData")
    public R selectData(@RequestBody String userString) throws Exception {
        JSONObject user = JSON.parseObject(userString);
        String code = (String) user.get("code");

        MiniApp miniApp = miniAppService.selectMiniAppByAppid(user.get("appid").toString());

        String appId = miniApp.getAppid();
        String appSecret = miniApp.getSecret();

        // 1. 获取AccessToken（使用Hutool的HttpUtil）
        String tokenUrl = String.format("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=%s&secret=%s", appId, appSecret);
        String tokenResult = HttpUtil.get(tokenUrl);
        String accessToken = JSON.parseObject(tokenResult).getString("access_token");

        // 2. 获取用户手机号（使用Hutool的HttpRequest）
        String url = String.format("https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=%s", accessToken);

        // 构建请求体JSON
        JSONObject requestBody = new JSONObject();
        requestBody.put("code", code);

        // 发送POST请求
        String responseBody = HttpRequest.post(url)
                .header("Content-Type", "application/json")
                .body(requestBody.toJSONString())
                .execute()
                .body();

        log.info("微信接口响应: {}", responseBody);

        return null;
    }

}
